package com.g2.admin.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.g2.admin.common.constant.StatusTypeEnums;
import com.g2.admin.model.po.UserOrgPo;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.g2.admin.model.po.UserOrgPo;
import com.g2.admin.dao.mapper.IUserOrgMapper;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class UserOrgService {
    @Autowired
    private IUserOrgMapper userorgMapper;

    public UserOrgPo getOrg(long id) {
        return userorgMapper.selectById(id);
    }

    public void delOrg(long id) {
        userorgMapper.deleteById(id);
    }

    public void addOrg(UserOrgPo userorg) {
        userorgMapper.insert(userorg);
    }

    public void updateOrg(UserOrgPo userorg) {
        userorgMapper.updateById(userorg);
    }

    /**
     * 获取所有数据列表，并组装为树形结构
     */
    public List<UserOrgPo> getOrgTree() {
        List<UserOrgPo> orgList = userorgMapper.selectList(new QueryWrapper<UserOrgPo>().lambda().eq(UserOrgPo::getStatus, StatusTypeEnums.StatusEnums.ENABLE));
        if (CollectionUtils.isEmpty(orgList)) {
            return null;
        }
        // 先把非第一级的权限分类
        Map<Long, List<UserOrgPo>> orgMap = orgList.stream().filter(x -> null != x.getParentId())
                .collect(Collectors.toMap(UserOrgPo::getParentId,
                        x -> Lists.newArrayList(x), (List<UserOrgPo> n, List<UserOrgPo> o) -> {
                            n.addAll(o);
                            return n;
                        }));
        orgList.forEach(x -> x.setChildren(orgMap.get(x.getId())));
        // 处理一级权限
        List<UserOrgPo> result = orgList.stream().filter(x -> null == x.getParentId()).collect(Collectors.toList());
        return result;
    }

}
